package com.niiwoo.civet.user.service.duboo;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.niiwoo.civet.snapdata.dto.request.SaveYXCreditDataReqDTO;
import com.niiwoo.civet.snapdata.enums.YXBillDelayStatusEnum;
import com.niiwoo.civet.snapdata.service.YXCreditCardDubboService;
import com.niiwoo.civet.user.dao.entity.UserCreditCardAuthInfo;
import com.niiwoo.civet.user.dto.request.UserCreditCardAuthInfoDTO;
import com.niiwoo.civet.user.service.UserYXCreditCardDubboService;
import com.niiwoo.civet.user.service.local.UserYXCreditCardService;
import com.niiwoo.tripod.base.component.PrivacyMasks;
import com.niiwoo.tripod.base.utils.FutureResponses;
import com.niiwoo.tripod.service.component.SnowflakeIdWorker;
import com.niiwoo.tripod.tiancheng.component.TianchengAuthCreditCardService;
import com.niiwoo.tripod.tiancheng.component.TianchengUserBehaviorAnalysisService;
import com.niiwoo.tripod.tiancheng.enums.FunctionCodeEnum;
import com.niiwoo.tripod.tiancheng.request.auth.YXCreditDataQueryRequest;
import com.niiwoo.tripod.tiancheng.request.df.CardniuCreditCardAnalysisRequest;
import com.niiwoo.tripod.tiancheng.response.auth.YXCreditDataQueryResponse;
import com.niiwoo.tripod.tiancheng.response.common.CardniuCreditCardAnalysisResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * @Author: wuke
 * @Description:
 * @Date: Created in 16:45 2018/3/6
 */
@Slf4j
@Service(version = "1.0.0")
public class UserYXCreditCardDubboServiceImpl implements UserYXCreditCardDubboService {
    @Reference(version = "1.0.0")
    private YXCreditCardDubboService yxCreditCardDubboService;
    @Autowired
    TianchengAuthCreditCardService tianchengAuthCreditCardService;
    @Autowired
    TianchengUserBehaviorAnalysisService tianchengUserBehaviorAnalysisService;
    @Autowired
    UserYXCreditCardService userYXCreditCardService;
    @Autowired
    private SnowflakeIdWorker snowflakeIdWorker;
    @Autowired
    PrivacyMasks privacyMasks;

    public void yxCreditDataQuery(){
        YXCreditDataQueryRequest request = new YXCreditDataQueryRequest();
        /*request.setEntryId("115");
        request.setHouseName("从雅婷");
        request.setIdCardNo("450821198901081932");
        request.setLoginName("12345");
        request.setPhone("13700000010");*/
        request.setEntryId("123456");
        request.setHouseName("连磊");
        request.setIdCardNo("420102197911110613");
        request.setLoginName("18672926885");
        request.setPhone("18672926885");
        request.setTransDate(new Date());
        request.setTransNo(String.valueOf(snowflakeIdWorker.nextId()));
        CompletableFuture<YXCreditDataQueryResponse> yxCompletableFuture = tianchengAuthCreditCardService.yxCreditDataQuery(request);
        YXCreditDataQueryResponse yxCreditDataQueryResponse = FutureResponses.get(yxCompletableFuture);
        log.info("yxCreditDataQuery.yxCreditDataQueryResponse={}", JSON.toJSONString(yxCreditDataQueryResponse));
    }

    public void queryCreditCardAnalysisFromTiancheng(){
        CardniuCreditCardAnalysisRequest request =  new CardniuCreditCardAnalysisRequest();
        request.setFromSource("1"); //来源.(1：信用卡贷；2：卡牛)
        request.setTransDate(new Date());
        request.setTransNo(String.valueOf(snowflakeIdWorker.nextId()));
        request.setUserId("0000a570-70a5-486e-a5cd-ffa5177198b2");
        request.setRealName("连磊");
        request.setIdentityCard("420102197911110613");
        request.setMobilePhone("18672926885");
        request.setLoginName("18672926885");
        request.setEntryId("123456");
        request.setFunctionCode(FunctionCodeEnum.CARDNIU_CREDIT_CARD_ANALYSIS.getBodyFunctionCode());
        CompletableFuture<CardniuCreditCardAnalysisResponse> completableFuture = tianchengUserBehaviorAnalysisService.postCardniuCreditCardAnalysis(request);
        CardniuCreditCardAnalysisResponse creditCardAnalysisResponse = FutureResponses.get(completableFuture);
        log.info("queryCreditCardAnalysisFromTiancheng.creditCardAnalysisResponse={}", JSON.toJSONString(creditCardAnalysisResponse));
    }

    public void saveYXCreditCardData(String userId){
        log.info("saveYXCreditCardData.userId={}",userId);
        //从天秤查询驭信信用卡数据
        YXCreditDataQueryResponse yxCreditDataQueryResponse = this.queryYXCreditDataFromTiancheng(userId);
        if(yxCreditDataQueryResponse==null){
            log.info("saveYXCreditCardData.userId={}调用天秤查询驭信信用卡数据返回为空",userId);
            return;
        }
        Integer tianChengStatus = yxCreditDataQueryResponse.getTianChengStatus();
        if(tianChengStatus==null || tianChengStatus.intValue()==1){
            log.info("saveYXCreditCardData.userId={}调用天秤查询驭信信用卡数据失败,message={}",userId,yxCreditDataQueryResponse.getMessage());
            return;
        }

        YXCreditDataQueryResponse.YXCreditRetData yxCreditRetData = yxCreditDataQueryResponse.getData();
        if(yxCreditRetData==null){
            log.info("saveYXCreditCardData.userId={}调用天秤查询驭信信用卡数据yxCreditRetData为空message={}",userId,yxCreditDataQueryResponse.getMessage());
            return;
        }
        if(!"SUCCESS".equals(yxCreditRetData.getRet())){
            log.info("saveYXCreditCardData.userId={}调用天秤查询驭信信用卡数据失败,errorCode={},errorMsg={}",userId,yxCreditRetData.getErrorCode(),yxCreditRetData.getErrorMsg());
            return;
        }

        YXCreditDataQueryResponse.YXCreditUserInfo yxCreditUserInfo = yxCreditRetData.getData();
        if(yxCreditRetData==null){
            log.info("saveYXCreditCardData.userId={}调用天秤查询驭信信用卡数据yxCreditRetData为空",userId);
            return;
        }

        SaveYXCreditDataReqDTO saveYXCreditDataReqDTO = new SaveYXCreditDataReqDTO();
        saveYXCreditDataReqDTO.setUserId(userId);
        saveYXCreditDataReqDTO.setCommonCreditCardId(yxCreditUserInfo.getCommonCreditCardId());
        saveYXCreditDataReqDTO.setIsSlightlyOverdue(this.convertStringToByte(yxCreditUserInfo.getIs_slightly_overdue()));
        saveYXCreditDataReqDTO.setIsMatchNetbankHouseHolder(this.convertStringToByte(yxCreditUserInfo.getIs_match_netbank_house_holder()));
        saveYXCreditDataReqDTO.setIsCardniuBlacklist(this.convertStringToByte(yxCreditUserInfo.getIs_cardniu_blacklist()));
        saveYXCreditDataReqDTO.setIsLackRepayment(this.convertStringToByte(yxCreditUserInfo.getIs_lack_repayment()));
        saveYXCreditDataReqDTO.setIsSeriouslyOverdue(this.convertStringToByte(yxCreditUserInfo.getIs_seriously_overdue()));
        this.setCreditCardAnalysisData(userId,saveYXCreditDataReqDTO);

        List<YXCreditDataQueryResponse.YXCreditCardInfo> lstNetBankCreditCardInfo = yxCreditUserInfo.getLstNetBankCreditCardInfo();
        List<SaveYXCreditDataReqDTO.YXCreditCardInfoReqDTO> yxCreditCardInfoReqList = new ArrayList<SaveYXCreditDataReqDTO.YXCreditCardInfoReqDTO>();
        for(YXCreditDataQueryResponse.YXCreditCardInfo cardInfo : lstNetBankCreditCardInfo){
            SaveYXCreditDataReqDTO.YXCreditCardInfoReqDTO cardInfoReqDTO = new SaveYXCreditDataReqDTO.YXCreditCardInfoReqDTO();
            cardInfoReqDTO.setCardId(cardInfo.getCard_id());
            cardInfoReqDTO.setBankName(cardInfo.getBank_name());
            cardInfoReqDTO.setCreditLimit(cardInfo.getCredit_limit());
            cardInfoReqDTO.setLimitAvail(cardInfo.getLimit_avail());
            cardInfoReqDTO.setFullCardNum(this.maskFullCardNum(cardInfo.getFull_card_num()));
            cardInfoReqDTO.setUpdateTime(cardInfo.getUpdateTime());
            yxCreditCardInfoReqList.add(cardInfoReqDTO);
        }
        saveYXCreditDataReqDTO.setYxCreditCardInfoReqList(yxCreditCardInfoReqList);

        List<YXCreditDataQueryResponse.YXCreditBillInfo> lstNetBankCreditBillInfo = yxCreditUserInfo.getLstNetBankCreditBillInfo();
        List<SaveYXCreditDataReqDTO.YXCreditBillInfoReqDTO> yxCreditBillInfoReqList = new ArrayList<SaveYXCreditDataReqDTO.YXCreditBillInfoReqDTO>();
        for(YXCreditDataQueryResponse.YXCreditBillInfo billInfo : lstNetBankCreditBillInfo){
            SaveYXCreditDataReqDTO.YXCreditBillInfoReqDTO billInfoReqDTO = new SaveYXCreditDataReqDTO.YXCreditBillInfoReqDTO();
            billInfoReqDTO.setCardId(billInfo.getCard_id());
            billInfoReqDTO.setMonth(billInfo.getMonth());
            billInfoReqDTO.setNewCharges(billInfo.getNew_charges());
            billInfoReqDTO.setIsFullRepayment(this.convertStringToByte(billInfo.getIs_full_repayment()));
            YXBillDelayStatusEnum yxBillDelayStatusEnum = YXBillDelayStatusEnum.getByTianchengStatus(billInfo.getDelay_status());
            billInfoReqDTO.setDelayStatus(yxBillDelayStatusEnum==null?null:yxBillDelayStatusEnum.getDatabaseStatus());
            yxCreditBillInfoReqList.add(billInfoReqDTO);
        }
        saveYXCreditDataReqDTO.setYxCreditBillInfoReqList(yxCreditBillInfoReqList);

        yxCreditCardDubboService.saveYXCreditCardData(saveYXCreditDataReqDTO);
    }

    private String maskFullCardNum(String fullCardNum){
        try {
            return privacyMasks.maskBankCard(fullCardNum);
        } catch (Exception e) {
            return fullCardNum;
        }
    }

    private void setCreditCardAnalysisData(String userId, SaveYXCreditDataReqDTO saveYXCreditDataReqDTO){
        try {
            CardniuCreditCardAnalysisResponse cardniuCreditCardAnalysisResponse = this.queryCreditCardAnalysisFromTiancheng(userId);
            if(cardniuCreditCardAnalysisResponse==null){
                log.info("setCreditCardAnalysisData.userId={}调用天秤查询信用卡分析数据返回为空",userId);
                return;
            }
            Integer statuc = cardniuCreditCardAnalysisResponse.getStatus();
            if(statuc==null || statuc.intValue()==1){
                log.info("setCreditCardAnalysisData.userId={}调用天秤查询信用卡分析数据失败,message={}",userId,cardniuCreditCardAnalysisResponse.getMessage());
                return;
            }

            CardniuCreditCardAnalysisResponse.Content content = cardniuCreditCardAnalysisResponse.getContent();
            if(content==null){
                log.info("setCreditCardAnalysisData.userId={}调用天秤查询信用卡分析数据返回content为空",userId);
                return;
            }
            String maxCreditQuota = content.getMaxCreditQuota();

            saveYXCreditDataReqDTO.setMaxCreditQuota(StringUtils.hasText(maxCreditQuota)?new BigDecimal(maxCreditQuota):null);
            saveYXCreditDataReqDTO.setCreditHistoryDuration(content.getCreditHistoryDuration());
        } catch (Exception e) {
            log.error("setCreditCardAnalysisData异常，userId={}",userId,e);
        }
    }

    private YXCreditDataQueryResponse queryYXCreditDataFromTiancheng(String userId){
        YXCreditDataQueryRequest request = userYXCreditCardService.getYXCreditDataQueryRequest(userId);
        request.setTransDate(new Date());
        request.setTransNo(String.valueOf(snowflakeIdWorker.nextId()));
        CompletableFuture<YXCreditDataQueryResponse> yxCompletableFuture = tianchengAuthCreditCardService.yxCreditDataQuery(request);
        YXCreditDataQueryResponse yxCreditDataQueryResponse = FutureResponses.get(yxCompletableFuture);
        return yxCreditDataQueryResponse;
    }
    //tianchengUserBehaviorAnalysisService
    private CardniuCreditCardAnalysisResponse queryCreditCardAnalysisFromTiancheng(String userId){
        CardniuCreditCardAnalysisRequest request =  userYXCreditCardService.getCreditCardAnalysisRequest(userId);
        request.setFromSource("1"); //来源.(1：信用卡贷；2：卡牛)
        request.setTransDate(new Date());
        request.setTransNo(String.valueOf(snowflakeIdWorker.nextId()));

        CompletableFuture<CardniuCreditCardAnalysisResponse> completableFuture = tianchengUserBehaviorAnalysisService.postCardniuCreditCardAnalysis(request);
        CardniuCreditCardAnalysisResponse creditCardAnalysisResponse = FutureResponses.get(completableFuture);
        return creditCardAnalysisResponse;
    }

    private Byte convertStringToByte(String str){
        if(!StringUtils.hasText(str)){
            return null;
        }
        return Byte.valueOf(str);
    }

    /**
     * 查询用户驭信信息
     *
     * @param userId
     * @return
     */
    @Override
    public UserCreditCardAuthInfoDTO queryUserCreditCardAuthInfo(String userId) {
        UserCreditCardAuthInfo userCreditCardAuthInfo = userYXCreditCardService.queryUserCreditCardAuthInfo(userId);
        UserCreditCardAuthInfoDTO userCreditCardAuthInfoDTO = null;
        if (userCreditCardAuthInfo != null) {
            userCreditCardAuthInfoDTO = new UserCreditCardAuthInfoDTO();
            BeanUtils.copyProperties(userCreditCardAuthInfo, userCreditCardAuthInfoDTO);
        }
        return userCreditCardAuthInfoDTO;
    }
}
